using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using UnityEngine;

namespace Gj
{
    public class CryptoTools
    {
        public static byte[] EncryptDES(byte[] encryptString, string encryptKey)
        {
            try
            {
                var rgbKey = Encoding.ASCII.GetBytes(encryptKey.Substring(0, 8));
                var rgbIV = Encoding.ASCII.GetBytes(encryptKey.Substring(encryptKey.Length - 8, 8));
                var dCSP = new DESCryptoServiceProvider();
                var mStream = new MemoryStream();
                var cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(encryptString, 0, encryptString.Length);
                cStream.FlushFinalBlock();
                return mStream.ToArray();
            }
            catch (Exception exception)
            {
                Debug.LogException(exception);
                return encryptString;
            }
        }

        public static byte[] DecryptDES(byte[] decryptString, string decryptKey)
        {
            try
            {
                var rgbKey = Encoding.ASCII.GetBytes(decryptKey.Substring(0, 8));
                var rgbIV = Encoding.ASCII.GetBytes(decryptKey.Substring(decryptKey.Length - 8, 8));
                var DCSP = new DESCryptoServiceProvider();
                var mStream = new MemoryStream();
                var cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(decryptString, 0, decryptString.Length);
                cStream.FlushFinalBlock();
                return mStream.ToArray();
            }
            catch (Exception exception)
            {
                Debug.LogException(exception);
                return decryptString;
            }
        }

        public static string Base64UrlEncodeNoPadding(byte[] buffer)
        {
            var base64 = Convert.ToBase64String(buffer);
            // Converts base64 to base64url.
            base64 = base64.Replace("+", "-");
            base64 = base64.Replace("/", "_");
            // Strips padding.
            base64 = base64.Replace("=", "");

            return base64;
        }
    }
}